package com.healthcloud.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;

/**
 * @author wangdi
 * @date 2018/4/17
 */
@Slf4j
public final class WebUtil {

    /**
     * 是否Ajax请求
     *
     * @param request
     * @return
     */
    public static boolean isAjax(ServletRequest request) {
        String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
        if ("XMLHttpRequest".equalsIgnoreCase(header)) {
            return true;
        }
        return false;
    }

    public static boolean isAjax(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        if ("XMLHttpRequest".equalsIgnoreCase(header)) {
            return true;
        }
        return false;
    }

    /**
     * 使用Response输出Json
     *
     * @param response
     */
    public static void out(ServletResponse response, ApiRes responseResult) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        try (PrintWriter out = response.getWriter()) {
            out.println(GsonUtil.obj2Json(responseResult));
        } catch (Exception e) {
            log.error(e + "输出JSON出错");
        }
    }
}
